package com.xia.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * 配置数据源，部分借助AI
 */
@Configuration
public class DataSourceConfig {

    /**
     * 配置数据源从application.yml中获取
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DruidDataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setMaxActive(10);  // 最大连接数
        ds.setMinIdle(2);  // 最小空闲连接数
        ds.setInitialSize(3); // 初始连接数
        ds.setMaxWait(6000); // 获取连接超时时间
        ds.setTimeBetweenEvictionRunsMillis(6000); // 配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        return ds;
    }

    /**
     * 创建代理数据源
     */
    @Primary // 设置为默认数据源
    @Bean("dataSource")
    public DataSource dataSourceProxy(DruidDataSource druidDataSource) {
        return new DataSourceProxy(druidDataSource);
    }

    /**
     * 创建MyBatis的SqlSessionFactory
     */
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource); // 关键：传入的是被代理的dataSource
        factoryBean.setTypeAliasesPackage("com.xia.domain");
        factoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
        return factoryBean.getObject();
    }

}
